package com.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.db.common.annotation.RequiredDept;
import com.db.common.pojo.TreeNode;
import com.db.dao.SysDeptDao;
import com.db.pojo.SysDept;
import com.db.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class SysDeptServiceImpl implements SysDeptService {

	@Autowired
	private SysDeptDao sysDeptDao;

	@RequiredDept(operation = "查询部门")
	@Transactional(readOnly = true)
	@Override
	public List<Map<String, Object>> findObjects() {
		List<Map<String, Object>> list = sysDeptDao.findObjects();
		return list;
	}

	@RequiredDept(operation = "删除部门")
	@Override
	public void deleteById(Integer id) {
		QueryWrapper<SysDept> wrapper = new QueryWrapper<>();
		wrapper.eq("parentId", id);
		Integer rows = sysDeptDao.selectCount(wrapper);
		if (rows > 0)
			throw new RuntimeException("有子部门,无法删除"); //还未定义全局异常类

		sysDeptDao.deleteById(id); //没有子部门才可以删除
	}

	@RequiredDept(operation = "查询部门树")
	@Override
	public List<TreeNode> findTree() {
		List<SysDept> depts = sysDeptDao.selectList(null);

		List<TreeNode> nodes = new ArrayList<>();

		for (SysDept dept :
				depts) {
			TreeNode treeNode = new TreeNode();
			treeNode.setId(dept.getId());
			treeNode.setName(dept.getName());
			treeNode.setParentId(dept.getParentId());
			nodes.add(treeNode);
		}
		return nodes;
	}

	@RequiredDept(operation = "新增部门")
	@Override
	public void insertObject(SysDept sysDept) {
		sysDeptDao.insert(sysDept);
	}

	@RequiredDept(operation = "更新部门")
	@Override
	public void updateObject(SysDept sysDept) {
		sysDeptDao.updateById(sysDept);
	}
}
